/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.controller.grant;

import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.util.TreeUtil;
import com.je.core.entity.extjs.JSONTreeNode;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.annotation.ControllerAuditLog;
import com.je.rbac.cache.FuncPermissionCache;
import com.je.rbac.rpc.PermissionRpcService;
import com.je.rbac.service.grant.RbacGrantFuncPermissionService;
import com.je.rbac.service.grant.RbacGrantMenuPermissionService;
import com.je.rbac.service.permission.GrantTypeEnum;
import com.je.rbac.service.permission.PermissionLoadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 机构授权
 */
@RestController
@RequestMapping(value = "/je/rbac/cloud/grant/org")
public class RbacGrantOrgController extends AbstractPlatformController {

    @Autowired
    private RbacGrantMenuPermissionService rbacGrantMenuPermissionService;
    @Autowired
    private RbacGrantFuncPermissionService rbacGrantFuncPermissionService;
    @Autowired
    private PermissionLoadService permissionLoadService;
    @Autowired
    private FuncPermissionCache funcPermissionCache;

    /**
     * 加载机构
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/loadOrgs"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "loadOrgs",operateTypeName = "加载机构树",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult loadOrgs(HttpServletRequest request) {
        String excludeDepartment = getStringParameter(request, "excludeDepartment");
        String refresh = getStringParameter(request, "refresh");
        //清空缓存并重新加载
        if ("1".equals(refresh)) {
            funcPermissionCache.clear();
            permissionLoadService.reloadAllOrgPermCache();
        }

        List<DynaBean> orgList;
        if ("1".equals(excludeDepartment)) {
            orgList = metaService.select("JE_RBAC_ORG", ConditionsWrapper.builder().ne("ORG_CODE","department").ne("ORG_CODE","develop"));
        } else {
            orgList = metaService.select("JE_RBAC_ORG",null);
        }
        JSONTreeNode rootNode = TreeUtil.buildRootNode();
        rootNode.setExpanded(true);
        JSONTreeNode eachNode;
        for (DynaBean eachOrg : orgList) {
            eachNode = new JSONTreeNode();
            eachNode.setText(eachOrg.getStr("ORG_NAME"));
            eachNode.setCode(eachOrg.getStr("ORG_CODE"));
            eachNode.setChecked(false);
            eachNode.setIcon("fal fa-landmark");
            eachNode.setNodeType("LEAF");
            eachNode.setNodeInfo(eachOrg.getStr("ORG_CODE"));
            eachNode.setLeaf(true);
            eachNode.setLayer("1");
            eachNode.setParent("ROOT");
            eachNode.setNodeInfoType("org");
            eachNode.setNodeInfo(eachOrg.getStr("ORG_CODE"));
            eachNode.setId(eachOrg.getStr("JE_RBAC_ORG_ID"));
            eachNode.setBean(eachOrg.getValues());
            eachNode.setExpanded(true);
            rootNode.getChildren().add(eachNode);
        }
        return BaseRespResult.successResult(rootNode);
    }

    /**
     * 保存机构菜单授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveOrgMenuPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveOrgMenuPermission",operateTypeName = "更新机构菜单授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveOrgMenuPermission(HttpServletRequest request) {
        String orgIds = getStringParameter(request, "orgIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");
        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        //更新权限
        rbacGrantMenuPermissionService.updateOrgMenuPermissions(GrantTypeEnum.MENU, orgIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存功能授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveOrgFuncPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveOrgFuncPermission",operateTypeName = "更新机构功能授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveOrgFuncPermission(HttpServletRequest request) {
        String orgIds = getStringParameter(request, "orgIds");
        String addedStrData = getStringParameter(request, "addedStrData");
        String deletedStrData = getStringParameter(request, "deletedStrData");

        if (Strings.isNullOrEmpty(addedStrData) && Strings.isNullOrEmpty(deletedStrData)) {
            return BaseRespResult.errorResult("无数据操作！");
        }
        rbacGrantFuncPermissionService.updateOrgFuncPermissions(GrantTypeEnum.FUNC, orgIds, addedStrData, deletedStrData);
        return BaseRespResult.successResult("保存授权成功！");
    }

    /**
     * 保存APP授权
     *
     * @param request
     * @return
     */
//    @AuthCheckPermission(value = {"pc-plugin-JE_CORE_RBAC-show"})
    @RequestMapping(value = {"/saveOrgAppPermission"}, method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ControllerAuditLog(moduleName = "角色授权模块",operateTypeCode = "saveOrgAppPermission",operateTypeName = "更新机构APP授权",logTypeCode = "securityManage",logTypeName = "安全管理")
    public BaseRespResult saveOrgAppPermission(HttpServletRequest request) {
        return BaseRespResult.errorResult("此版本不包括此功能！");
    }

}
